import 'package:after_sale_plugin/package_bridge.dart';
import 'package:inmotion_pro/config/conf.dart';
import 'package:inmotion_pro/generated/l10n.dart';
import 'package:inmotion_pro/routes/app_routes.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:lx_widgets_library/lx_widgets_library.dart';
import 'package:pull_to_refresh_flutter3/pull_to_refresh_flutter3.dart';
import 'routes/app_pages.dart';
import 'service/translation_service.dart';

void main() async {
  // 初始化插件
  await LxWidgetsLibrary.initialize(ThemeColorType.inmotion);

  // 配置系统状态栏样式
  Conf.setSystemUIOverlayStyle();

  // 初始化服务
  Conf.initService();

  // 初始化加载动画
  Conf.initLoading();

  // 初始化 Flutter 框架与引擎的连接： 建立 Dart 代码与平台原生代码之间的桥梁
  WidgetsFlutterBinding.ensureInitialized();

  // 初始化SentryFlutter服务
  // Conf.initSentryFlutter(() => runApp(const MyApp()));

  TranslationService.saveLocale(TranslationService.chineseLocale);

  runApp(const MyApp());
}

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  // 路由列表
  List<GetPage> routeList = AppPages.routes;

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    // 将售后插件的路由添加到应用的路由列表中
    routeList.addAll(AfterSalePluginBridge.to.routes);
    debugPrint("当前语言环境: ${TranslationService.getLocale()}");
    // 初始化ScreenUtil
    return ScreenUtilInit(
      designSize: const Size(375, 812), // 设计稿尺寸（单位：dp）
      minTextAdapt: true, // 是否根据宽度/高度中的最小值适配文字
      splitScreenMode: true, // 支持分屏尺寸
      builder: (context, child) {
        return GetMaterialApp(
          debugShowCheckedModeBanner: false, // 关掉模拟器右上角debug图标
          darkTheme: ThemeData.dark(), // 深色主题
          themeMode: ThemeMode.dark, // 强制使用深色模式
          theme: ThemeData.dark().copyWith(
            appBarTheme: const AppBarTheme(
              systemOverlayStyle: SystemUiOverlayStyle.light, // 浅色状态栏文字
            ),
          ),
          localizationsDelegates: const [
            RefreshLocalizations.delegate, // 下拉刷新国际化
            S.delegate, // 自动生成的代理:flutter pub run intl_utils:generate
            GlobalMaterialLocalizations.delegate, // 官方 Material 组件多语言
            GlobalWidgetsLocalizations.delegate, // 基础 Widget 多语言（如文本方向）
            GlobalCupertinoLocalizations.delegate, // iOS 风格组件多语言
          ],
          supportedLocales: S.delegate.supportedLocales, // 支持的语言列表
          locale: TranslationService.getLocale(), // 使用TranslationService获取当前语言
          translations: TranslationService(), // 使用TranslationService管理翻译
          fallbackLocale: TranslationService.fallbackLocale, // 如果无法匹配当前语言，则使用英文
          builder: FlutterSmartDialog.init(
            builder: (context, child) {
              // 限制文字缩放比例在1.0到1.4之间，防止字体过大导致布局错乱
              final mediaQuery = MediaQuery.of(context);
              final limitedTextScaler =
                  mediaQuery.textScaler.scale(1.0).clamp(1.0, 1.4);
              return MediaQuery(
                data: mediaQuery.copyWith(
                  textScaler: TextScaler.linear(limitedTextScaler),
                ),
                child: FlutterEasyLoading(
                  child: child,
                ),
              );
            },
          ),
          initialRoute: AppRoutes.LAUNCH,
          getPages: routeList,
        );
      },
    );
  }
}
